package com.iefgames.cs.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.iefgames.cs.manager.PopleManager;
import com.iefgames.cs.pople.Pople;
import com.iefgames.cs.shout.MessageShout;
import com.iefgames.cs.shout.AbstractShout;

public class Message extends HttpServlet {
	private static final long serialVersionUID = -9121048432269599505L;

	private Log logger = LogFactory.getLog(Message.class);
	
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Enumeration<String> names = request.getParameterNames();
		
		String name = null;
		ArrayList<String> params = new ArrayList<String>();
		while (names.hasMoreElements()) {
			params.add((name = names.nextElement()) + "=" + request.getParameter(name));
		}
		logger.debug("------>" + request.getRequestURI() + " " + params.toString());
		
		String usUuid = request.getParameter("usUuid");
		String csUuid = request.getParameter("csUuid");
		String msg = request.getParameter("msg");
		boolean isCs = Boolean.parseBoolean(request.getParameter("isCs"));
		
		MessageShout shout = new MessageShout();
		shout.setMsg(msg);
		shout.setUsUuid(usUuid);
		shout.setCsUuid(csUuid);
		shout.setCs(isCs);
		
		Pople us = PopleManager.get(usUuid);
		Pople cs = PopleManager.get(csUuid);
		
		if (us == null) {
			logger.info(usUuid + "is offline");
			return;
		}
		
		if (cs == null) {
			logger.info(csUuid + "is offline");
			return;
		}
		
		us.addMsg(shout);
		cs.addMsg(shout);
		
		us.getContinuation().resume();
		logger.debug("resume uuid is " + us.getUuid());
		cs.getContinuation().resume();
		logger.debug("resume uuid is " + cs.getUuid());
	}
}
